package com.nanyang.tms.common.util;


import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.apache.commons.lang3.StringUtils;
import org.krysalis.barcode4j.HumanReadablePlacement;
import org.krysalis.barcode4j.impl.codabar.CodabarBean;
import org.krysalis.barcode4j.impl.code39.Code39Bean;
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;
import org.krysalis.barcode4j.tools.UnitConv;

public class Test {

    /**
     * 生成文件
     *
     * @param msg
     * @param path
     * @return
     */
    public  static  File generateFile(String msg, String path) {
        File file =  new  File(path);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        try  {
            generate(msg,  new  FileOutputStream(file));
        }  catch  (FileNotFoundException e) {
            throw  new  RuntimeException(e);
        }
        return  file;
    }

    /**
     * 生成字节
     *
     * @param msg
     * @return
     */
    public  static  byte [] generate(String msg) {
        ByteArrayOutputStream ous =  new  ByteArrayOutputStream();
        generate(msg, ous);
        return  ous.toByteArray();
    }

    /**
     * 生成到流
     *
     * @param msg
     * @param ous
     */
    public  static  void  generate(String msg, OutputStream ous) {
        if  (StringUtils.isEmpty(msg) || ous ==  null ) {
            return ;
        }

        CodabarBean bean =  new  CodabarBean();

        // 精细度
        final  int  dpi =  150 ;
        // module宽度
        final  double  moduleWidth = UnitConv.in2mm( 1.0f / dpi);
        System.out.println(moduleWidth);

        // 配置对象
        bean.setModuleWidth(1.5);
        bean.setWideFactor( 2.5 );
        bean.doQuietZone( false );
        bean.setHeight(72);
        bean.setMsgPosition(HumanReadablePlacement.HRP_NONE);

        String format =  "image/png" ;
        try  {

            // 输出到流
            BitmapCanvasProvider canvas =  new  BitmapCanvasProvider(ous, format, dpi,
                    BufferedImage.TYPE_BYTE_BINARY,  false ,  0 );

            // 生成条形码
            bean.generateBarcode(canvas, msg);

            // 结束绘制
            canvas.finish();
        }  catch  (IOException e) {
            throw  new  RuntimeException(e);
        }
    }

    public  static  void  main(String[] args) {
        String msg =  "c$610342d" ;
        // FileOutputStream读取流的时候如果是文件夹，就会出错，无论怎么读，都拒绝访问，应该在读取的目录后面加上文件名！
        String path =  "/Users/lv/Documents/workspace/nanyang-cloud/nanyang-cloud/1.png" ;
        long startJobTs2 = System.currentTimeMillis();

        generateFile(msg, path);
        System.out.println("总耗时3:" + (System.currentTimeMillis() - startJobTs2) + "ms");

    }
}
